from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort
from datetime import datetime
from flaskr.auth import login_required
from flaskr.db import get_db
from flaskr.utils.get_hot_news import get_timestamp, weibo
bp = Blueprint('blog', __name__)

@bp.route('/')
def index():
    db = get_db()

    # 查询昨日的时间的文章
    time_stamp, date_info = get_timestamp()

    sql_cmd = "SELECT p.id, title, body, created, author_id, username"\
        " FROM post p JOIN user u ON p.author_id = u.id" \
        " WHERE DATE(created) < ?"\
        " ORDER BY created DESC"
    content_last_data = db.execute(sql_cmd, (date_info[0],)).fetchall()

    # print(date_info[0], date_info[1])
    # time_stamp = get_timestamp()
    # print(time_stamp)
    # response_status, news_dict = weibo(time_stamp, data_path='')
    news_dict= {'author':'test'}
    # 查询今天的内容
    sql_cmd = "SELECT p.id, title, body, created, author_id, username" \
        " FROM post p JOIN user u ON p.author_id = u.id"\
        " WHERE DATE(created) = ?"\
        " ORDER BY created DESC"
    today_record_data=db.execute(sql_cmd, (date_info[0],)).fetchall()


    # print(today_record_data[0])
    return render_template('blog/index.html',
                           content_last_data=content_last_data,
                           today_record_data=today_record_data,
                           news_items=news_dict)


@bp.route('/create', methods=('GET', 'POST'))
@login_required
def create():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            time_stamp, _ = get_timestamp()
            db = get_db()
            db.execute(
                'INSERT INTO post (title, body, author_id, created)'
                ' VALUES (?, ?, ?, ?)',
                (title, body, g.user['id'], time_stamp)
            )
            db.commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/create.html')

def get_post(id, check_author=True):
    post = get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id = ?',
        (id,)
    ).fetchone()

    if post is None:
        abort(404, f"Post id {id} doesn't exist.")

    if check_author and post['author_id'] != g.user['id']:
        abort(403)

    return post

@bp.route('/<int:id>/update', methods=('GET', 'POST'))
@login_required
def update(id):
    post = get_post(id)

    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'UPDATE post SET title = ?, body = ?'
                ' WHERE id = ?',
                (title, body, id)
            )
            db.commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/update.html', post=post)


@bp.route('/<int:id>/delete', methods=('POST',))
@login_required
def delete(id):
    get_post(id)
    db = get_db()
    db.execute('DELETE FROM post WHERE id = ?', (id,))
    db.commit()
    return redirect(url_for('blog.index'))